package com.example.demo.controller;

import com.example.demo.AccessToken.ProviderToken;
import com.example.demo.Privider.AccessProvider;
import com.example.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @author redjava
 * @create 2021-07-20 12:28
 */
@Controller
public class AccessTokenController {
    @Autowired
    private ProviderToken providerToken;
    @Autowired
    private AccessProvider accessProvider;
    @Autowired
    private User user;

    @Value("${gitee.client.id}")
    private String clientId;
    @Value("${gitee.client.secret}")
    private String clientSecret;
    @Value("${gitee.redirect.uri}")
    private String redirectUri;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletRequest request){
        providerToken.setClient_id(clientId);
        providerToken.setCode(code);
        providerToken.setRedirect_uri(redirectUri);
        providerToken.setState(state);
        providerToken.setClient_secret(clientSecret);
        String token = accessProvider.getToken(providerToken);
        User user = accessProvider.getUser(token);
        if (user != null) {
            //登录成功，写cookie和session
            request.getSession().setAttribute("user",user);
            return "redirect:index";
        }else{
            //登录失败，重新登录
            return "redirect:index";
        }
    }
}
